var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

/*引入路由配置*/
const loginRouter = require("./routes/login")
const userinfoRouter = require("./routes/userinfo")
const powerRouter = require("./routes/power")
const uploadRouter = require("./routes/upload")
const imageRouter = require("./routes/image")

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));//配置页面文件夹
app.set('view engine', 'ejs');//配置模板引擎

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
//去除304 http缓存状态码
app.disable('etag');

/*解决跨域问题*/
app.all('/*', function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With');
  res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
  if (req.method === 'OPTIONS') {
    res.sendStatus(200);
  } else {
    next();
  }
});

app.all("/*", function (req, res, next) {
  if (req.cookies.loginInfo) {
    next();
  } else {
    const whiteSheet = ["/", "/login"];
    let go = false;
    for (let i = 0; i < whiteSheet.length; i++) {
      if (req.url === whiteSheet[i]) {
        go = true;
        break;
      }
    }
    if (go) {
      next();
    } else {
      if (req.xhr) {
        res.json({code: 401, msg: "未登录"})
      } else {
        res.header("Content-Type", "text/html;charset=utf-8");
        res.write(`<script>alert('请先登录！');top.location.replace("/")</script>`);
      }
    }
  }
})

/*挂载路由*/
app.use('/', loginRouter);
app.use('/userinfo', userinfoRouter);
app.use('/power', powerRouter);
app.use('/upload', uploadRouter);
app.use('/image', imageRouter);

/*设置统一的编码格式*/
app.use(function (req, res, next) {
  req.setEncoding("utf-8");
  res.header("Content-Type","application/json;charset=utf-8")
  next();//放行
})

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});



module.exports = app;
